#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: main.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Main script

import time
import threading
import Queue
import random

import gtk

from vazaarlib.gui import GUI
from vazaarlib.utils import get_logger
from vazaarlib.provider import DataProvider
from vazaarlib.config import ConfigManager
from vazaarlib.store import StoreManager
from vazaarlib.query import QueryManager
from vazaarlib.vstore import VirtualStore

class Vazaar:
    """
    This class launch the GuiPart and the worker thread.
    """

    def __init__(self):
        """
        This start the GUI in a asynchronous thread.
        We are in the "main" thread of the application, wich will later
        be used by the gui as well. We spawn a new thread for the worker.
        """
        gtk.gdk.threads_init()
        self.settings = {}
        self.message  = ""
        self.fraction = 0.1
        self.percentaje = ''
        self.cfgmgr = ConfigManager(self)
        self.store = StoreManager(self)
        self.ask = QueryManager(self.store.get_graph())  # Query Manager
        self.vstore     = VirtualStore(self, self.ask) # Vir Store
        self.log = get_logger('Backend')
        self.qin = Queue.Queue()
        self.qout = Queue.Queue()
        self.provider   = DataProvider(self)            # Data Provider
        self.log.info('Backend initialized')
        self.gui = GUI(self, self.qin, self.qout, self.ask)
        self.running = True
        self.incoming_thread = threading.Thread(target=self.process_incoming)
        self.incoming_thread.setDaemon(True)
        self.incoming_thread.start()
        #gtk.threads_enter()
        gtk.main()
        self.running = False
        #gtk.threads_leave()

    def set_message(self, message):
        """ keep a message from provider """
        self.message = message

    def get_message(self):
        """ set message from provider"""

        return self.message

    def set_fraction(self, fraction):
        """ set fraction from provider """
        self.fraction = fraction

    def get_fraction(self):
        """ get fraction from provider """
        return self.fraction

    def set_percentaje(self, percentaje):
        """ set porcentaje from provider """
        self.percentaje = percentaje

    def get_percentaje(self):
        """ get porcentaje from provider """
        return self.percentaje


    def process_incoming(self):
        """
        This is where the blocking I/O job is being done.
        """
        while self.running:
            while self.qin.qsize():
                #self.log.debug("There are stuff in qin")
                try:
                    job = self.qin.get(0)
                    self.gui.current_job_id = job.id
                    # Lets process job
                    #self.log.debug("Job[%d]: qin got new stuff (%30s)"
                    # \% (job.id, job.label))
                    self.provider.prepare(job.label)
                    self.provider.run(job.id)

                    #for s, p, o in self.provider.store:
                    #    self.store.add_triple(s, p, o)
                    #self.store.do_commit()

                    time.sleep(random.random()*6)
                    #self.vstore.describe()
                    #job.result='we would store the resutl here'
                    self.gui.current_job_id = None
                    self.qout.put(job)
                except Queue.Empty:
                    pass
            time.sleep(2)


    def cancel_current_jobs(self):
        """ cancel all current jobs"""
        while self.qin.qsize():
            job = self.qin.get(0)
            self.log.warning("Canceling job %d" % job.id)
            self.gui.actions.update_statusbar("Canceling job %d" % job.id)
            del job

    def stop_backend(self):
        """ stop backend """
        self.cancel_current_jobs()
        self.provider.stop()
        self.store.close()
        self.log.info("Backend stopped")
